package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.dto.FavoriteAddDTO;
import com.ruoyi.system.dto.FavoriteQueryDTO;
import com.ruoyi.system.dto.ProjectDTO;
import com.ruoyi.system.dto.kujiale.PageResponse;
import com.ruoyi.system.dto.kujiale.info.RenderingImage;
import com.ruoyi.system.dto.kujiale.pano.RoamItem;
import com.ruoyi.system.entity.FavoriteDO;
import com.ruoyi.system.enums.SpaceTypeEnum;
import com.ruoyi.system.mapper.FavoriteMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.PageConvertUtil;
import com.ruoyi.system.utils.SysUserUtils;
import com.ruoyi.system.vo.FavoriteVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 收藏服务实现类
 * 
 * @author ruoyi
 * @since 2024-01-01
 */
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, FavoriteDO> implements IFavoriteService {

    @Resource
    private FavoriteMapper favoriteMapper;

    @Resource
    private DesignerService designerService;

    @Resource
    private CaseService caseService;

    @Resource
    private DesignSchemeService designSchemeService;

    @Resource
    private KuJiaLeService kuJiaLeService;

    @Resource
    private DesignBaseService designBaseService;

    @Resource
    private ProjectService projectService;

    @Override
    public boolean addFavorite(Long userId, FavoriteAddDTO favoriteAddDTO) {
        // 1. 检查是否已收藏
        FavoriteDO existingFavorite = this.lambdaQuery().eq(FavoriteDO::getUserId, userId)
                .eq(FavoriteDO::getBusinessType, favoriteAddDTO.getBusinessType())
                .eq(FavoriteDO::getBusinessId, favoriteAddDTO.getBusinessId())
                .eq(FavoriteDO::getIsDeleted, 0)
                .one();
        
        if (existingFavorite != null) {
            throw new ServiceException("您已经收藏过了");
        }

        // 2. 创建收藏记录
        FavoriteDO favorite = new FavoriteDO();
        favorite.setUserId(userId);
        favorite.setBusinessType(favoriteAddDTO.getBusinessType());
        favorite.setBusinessId(favoriteAddDTO.getBusinessId());
        favorite.setBusinessName(favoriteAddDTO.getBusinessName());
        favorite.setBusinessImage(favoriteAddDTO.getBusinessImage());
        favorite.setCreateTime(LocalDateTime.now());
        favorite.setUpdateTime(LocalDateTime.now());
        favorite.setIsDeleted(0);

        return favoriteMapper.insert(favorite) > 0;
    }

    @Override
    public boolean removeFavorite(Long userId, String businessType, Long businessId) {
        // 1. 查找收藏记录
        FavoriteDO favorite = this.lambdaQuery().eq(FavoriteDO::getUserId, userId)
                .eq(FavoriteDO::getBusinessType, businessType)
                .eq(FavoriteDO::getBusinessId, businessId)
                .eq(FavoriteDO::getIsDeleted, 0)
                .one();

        if (favorite == null) {
            throw new ServiceException("收藏记录不存在");
        }

        // 2. 逻辑删除
        favorite.setIsDeleted(1);
        favorite.setUpdateTime(LocalDateTime.now());
        
        return favoriteMapper.deleteById(favorite) > 0;
    }

    @Override
    public List<FavoriteVO> getUserFavorites(FavoriteQueryDTO queryDTO) {
        // 1. 构建查询条件
        LambdaQueryWrapper<FavoriteDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FavoriteDO::getUserId, queryDTO.getUserId());
        queryWrapper.eq(FavoriteDO::getIsDeleted, 0);
        
        if (StringUtils.hasText(queryDTO.getBusinessType())) {
            queryWrapper.eq(FavoriteDO::getBusinessType, queryDTO.getBusinessType());
        }
        
        queryWrapper.orderByDesc(FavoriteDO::getCreateTime);

        // 2. 查询收藏记录
        List<FavoriteDO> favorites = favoriteMapper.selectList(queryWrapper);

        List<FavoriteVO> result = new ArrayList<>();
        Map<Long, DesignerGen> collect1 = null;
        Map<Long, CasesGen> collect2 = null;
        Map<Long, DesignScheme> collect3 = null;
        if (!favorites.isEmpty()) {
            Set<Long> collect = favorites.stream().map(FavoriteDO::getBusinessId).collect(Collectors.toSet());
            if ("designer".equals(queryDTO.getBusinessType())) {
                List<DesignerGen> list = designerService.lambdaQuery().in(DesignerGen::getId, collect).list();
                collect1 = list.stream().collect(Collectors.toMap(DesignerGen::getId, designer -> designer));
            } else if ("cases".equals(queryDTO.getBusinessType())) {
                List<CasesGen> list = caseService.lambdaQuery().in(CasesGen::getId, collect).list();
                collect2 = list.stream().collect(Collectors.toMap(CasesGen::getId, cases -> cases));
            } else if ("designBase".equals(queryDTO.getBusinessType())) {
                List<DesignScheme> schemes = designSchemeService.lambdaQuery().in(DesignScheme::getId, collect).list();
                if (CollectionUtil.isNotEmpty(schemes)) {
                    for (DesignScheme scheme : schemes) {
                        if (scheme.getUseOnlineDesign() != null && scheme.getUseOnlineDesign().equals(1)
                                && com.ruoyi.common.utils.StringUtils.isNotBlank(scheme.getOnlineDesignId())) {
                            scheme.setImages(getKujialeImg(scheme.getOnlineDesignId()));
                        }
                        if (scheme.getDesignBaseId() != null) {
                            DesignBase designBase = designBaseService.getById(scheme.getDesignBaseId());
                            if (designBase != null) {
                                ProjectDTO project = projectService.getProjectById(designBase.getProjectId());
                                scheme.setProject(project);
                            }
                            scheme.setDesignBase(designBase);
                        }

                    }
                }
                collect3 = schemes.stream().collect(Collectors.toMap(DesignScheme::getId, designBase -> designBase));
            }

        }

        // 3. 转换为VO
        for (FavoriteDO favorite : favorites) {
            FavoriteVO vo = new FavoriteVO();
            BeanUtils.copyProperties(favorite, vo);
            vo.setBusinessTypeName(getBusinessTypeName(favorite.getBusinessType()));
            if ("designer".equals(favorite.getBusinessType()) && collect1 != null) {
                DesignerGen designerGen = collect1.get(favorite.getBusinessId());
                vo.setDesignerGen(designerGen);
            } else if ("cases".equals(favorite.getBusinessType()) && collect2 != null) {
                CasesGen casesGen = collect2.get(favorite.getBusinessId());
                vo.setCasesGen(casesGen);
            } else if ("designBase".equals(favorite.getBusinessType())) {
                DesignScheme designScheme = collect3.get(favorite.getBusinessId());
                vo.setDesignScheme(designScheme);
            }
            result.add(vo);
        }

        return result;
    }

    @Override
    public boolean isFavorited(Long userId, String businessType, Long businessId) {
        FavoriteDO favorite = this.lambdaQuery().eq(FavoriteDO::getUserId, userId)
                .eq(FavoriteDO::getBusinessType, businessType)
                .eq(FavoriteDO::getBusinessId, businessId)
                .eq(FavoriteDO::getIsDeleted, 0)
                .one();

        return favorite != null;
    }

    @Override
    public List<Long> getFavoritedBusinessIds(Long userId, String businessType, List<Long> businessIds) {
        if (businessIds == null || businessIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 1. 查询用户收藏的业务ID列表
        LambdaQueryWrapper<FavoriteDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FavoriteDO::getUserId, userId);
        queryWrapper.eq(FavoriteDO::getBusinessType, businessType);
        queryWrapper.in(FavoriteDO::getBusinessId, businessIds);
        queryWrapper.eq(FavoriteDO::getIsDeleted, 0);
        queryWrapper.select(FavoriteDO::getBusinessId);

        List<FavoriteDO> favorites = favoriteMapper.selectList(queryWrapper);
        
        // 2. 提取业务ID列表
        return favorites.stream()
                .map(FavoriteDO::getBusinessId)
                .collect(Collectors.toList());
    }

    @Override
    public int getFavoriteCount(String businessType, Long businessId) {
        LambdaQueryWrapper<FavoriteDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FavoriteDO::getBusinessType, businessType);
        queryWrapper.eq(FavoriteDO::getBusinessId, businessId);
        queryWrapper.eq(FavoriteDO::getIsDeleted, 0);

        return Math.toIntExact(favoriteMapper.selectCount(queryWrapper));
    }

    /**
     * 获取业务类型名称
     */
    private String getBusinessTypeName(String businessType) {
        if (!StringUtils.hasText(businessType)) {
            return "";
        }
        
        switch (businessType) {
            case "designer":
                return "设计师";
            case "cases":
                return "案例";
            default:
                return businessType;
        }
    }

    private List<DesignSchemeImage> getKujialeImg(String kujialeDesignId) {
        PageConvertUtil.PageParam convert = PageConvertUtil.convert(1, 50);
        // 明确返回数据类型为 PageResponse，Swagger 可通过 @ApiResponse 关联
        PageResponse<RenderingImage> pageResponse = kuJiaLeService.renderpicList(kujialeDesignId, convert.getStart(), convert.getNum());
        List<RenderingImage> result = pageResponse.getResult();
        if (CollectionUtil.isEmpty(result)) {
            return null;
        }
//        Map<Integer, String> picTypeNameMapeMap = ImmutableMap.of(0, "普通图", 1, "全景图", 3, "俯视图");
        List<DesignSchemeImage> resultList = Lists.newArrayList();

        for (RenderingImage renderingImage : result) {
            DesignSchemeImage designSchemeImage = new DesignSchemeImage();
            resultList.add(designSchemeImage);

            if ( com.ruoyi.common.utils.StringUtils.isBlank(renderingImage.getImg())) {
                continue;
            }
            designSchemeImage.setFilePath(renderingImage.getImg());
            SpaceTypeEnum byLabel = SpaceTypeEnum.getByLabel(renderingImage.getRoomName());
            if (byLabel != null) {
                designSchemeImage.setSpaceName(byLabel.getLabel());
                designSchemeImage.setSpaceType(byLabel.getValue());
            } else {
                designSchemeImage.setSpaceName(com.ruoyi.common.utils.StringUtils.isBlank(renderingImage.getRoomName()) || renderingImage.getRoomName().equals("未知") ? SpaceTypeEnum.OTHER.getLabel() : renderingImage.getRoomName());
                designSchemeImage.setSpaceType(SpaceTypeEnum.OTHER.getValue());
            }

        }
        return resultList;

    }
}
